from flask import Flask, request, jsonify, make_response
import json
import time
from databases import db

app = Flask(__name__)
# 跨域
from flask_cors import CORS

CORS(app)
# 动态更新
from settings import Sttings

app.config.from_object(Sttings)


# 钩子函数
# 开始时间
@app.before_request
def before_request():
    # 获取当前url
    url = request.url
    # 获取到当前时间戳
    nowtime = time.time()
    sql = "insert into gouzi(url,stime) values ('%s','%s')" % (url, nowtime)
    db.insert(sql)
# 结束时间
@app.after_request
def after_request(response):
    # 获取当前url
    url = request.url
    # 获取到当时间戳
    nowtime = time.time()
    # 根据url去数据库中查询
    sql = "select * from gouzi where url='%s' and etime is null" % (url)
    res = db.findone(sql)
    sql1 = "update gouzi set etime='%s' where id = %d" % (nowtime, res['id'])
    db.insert(sql1)
    return make_response(response)


@app.route('/', methods=['GET', 'POST'])
def add():
    if request.method == 'POST':
        # 添加
        # 获取用户输入
        data = json.loads(request.data)
        print(data)
        title = data['biaoti']
        sql = "insert into news(biaoti) values('%s')" %(title)
        db.insert(sql)
        # 返回
        return ({"code": 200})
    else:
        return ({"code": 10010})



if __name__ == '__main__':
    app.run(host="0.0.0.0")
